package com.tony.thread;

import java.util.concurrent.CountDownLatch;

/**
 * T1,T2,T3三个线程，保证T1执行完执行T2，T2执行完执行T3
 */
public class OneByOne {
    public static void main(String[] args) {
        concurrent();
        //method1();
    }

    public static int threadCount = 10;
    public  static void concurrent(){
        final CountDownLatch countDownLatch =  new CountDownLatch(threadCount);
        for(int i=0;i<threadCount;i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        countDownLatch.await();
                        method1(Thread.currentThread().getName());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            countDownLatch.countDown();
        }
    }

    /**
     * 通过join方式实现
     */
    public static void method1(String name){
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(name+" t1 finished!");
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(300);
                    t1.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(name+" t2 finished!");
            }
        });

        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(100);
                    t2.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(name+" t3 finished");
            }
        });

//        t3.start();
//        t2.start();
//        t1.start();
        t1.start();
        t2.start();
        t3.start();
    }

    public static void menthod2() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "执行完毕");
            }
        };
        Thread t1 = new Thread(runnable, "t1");
        Thread t2 = new Thread(runnable, "t2");
        Thread t3 = new Thread(runnable, "t3");

        try {
            t1.start();
            t1.join();
            t2.start();
            t2.join();
            t3.start();
            t3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
